﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Drawing;

namespace ChatTool
{
    public class DesktopShare
    {
        private FormChatToOne formChatToOne;
        private UserClient userClient;
        private bool isExit;

        public DesktopShare(FormChatToOne formChatToOne)
        {
            this.formChatToOne = formChatToOne;
        }
        /// <summary>
        /// 连接服务器
        /// </summary>
        public UserClient ConnectServer()
        {
            TcpClient client = new TcpClient(AddressFamily.InterNetwork);
            try
            {
                IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(formChatToOne.UserClient.User.Ip), formChatToOne.UserClient.User.ListenerPort);
                client.Connect(ipe);//连接服务器
                userClient = new UserClient(client);

                Thread receiveThread = new Thread(ReceiveServerData);
                receiveThread.IsBackground = true;
                receiveThread.Start();
                return userClient;
            }
            catch
            {
                client.Close();
                return null;
            }
        }
        /// <summary>
        /// 接受服务端信息的线程方法体
        /// </summary>
        private void ReceiveServerData(object clientObj)
        {
            while (isExit == false)
            {
                try
                {
                    string command = userClient.Br.ReadString().ToLower();
                    switch (command.ToLower())
                    {
                        case "refuse"://对方拒绝共享桌面的请求 关闭连接 回复Button 的 Text 
                            Close();
                            MessageBox.Show("对方拒绝了你的桌面共享请求!");
                            return;
                        case "agree"://表示开始接收服务器发过来的桌面截图信息
                            SendShareImageThread();
                            break;
                        case "stop":
                            Close();
                            MessageBox.Show("对方停止了你的桌面共享!");
                            return;
                        default:
                            break;
                    }
                }
                catch (Exception)
                {
                    if (isExit == false)
                    {
                        userClient.Close();
                        MessageBox.Show("与对方断开了连接,可能对方停止了桌面共享!");
                        return;
                    }
                    userClient.Close();
                    return;
                }
            }
        }

        private void SendShareImageThread()
        {
            Thread sendThread = new Thread(SendShareImage);
            sendThread.IsBackground = true;
            sendThread.Start();
        }
        private void SendShareImage()
        {
            while (isExit == false)
            {
                Bitmap desktopImage = null;
                try
                {
                    //获取桌面的数据
                    desktopImage = new Bitmap(this.formChatToOne.ShareRegion.Width, this.formChatToOne.ShareRegion.Height);
                    using (Graphics g = Graphics.FromImage(desktopImage))
                    {
                        g.CopyFromScreen(this.formChatToOne.ShareRegion.Location, new Point(0, 0), desktopImage.Size);
                    }
                    using (MemoryStream ms = new MemoryStream())
                    {
                        if (desktopImage != null)
                        {
                            desktopImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                            byte[] bs = ms.GetBuffer();
                            NetManager.SendBytesMsgToServer(userClient, bs);
                            Thread.Sleep(100);
                            //Thread.Sleep((Screen.AllScreens[0].Bounds.Width - desktopImage.Width) / 100 * 10);
                        }
                    }
                }
                catch (Exception ee)
                {
                    userClient.Close();
                    this.formChatToOne.SetButtonText("tsbDesktopShare", "桌面共享");
                    MessageBox.Show("发送桌面共享图片异常: " + ee.Message);
                    return;
                }
                finally
                {
                    desktopImage.Dispose();
                    desktopImage = null;
                }
            }
        }
        /// <summary>
        /// 关闭桌面共享
        /// </summary>
        public void Close()
        {
            this.isExit = true;
            userClient.Close();
            this.formChatToOne.SetButtonText("tsbDesktopShare", "桌面共享");
        }
    }
}
